package cn.gong.base.ui;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.gong.base.Base;
import cn.gong.base.config.PhoneParameters;
import cn.gong.http.bean.HttpTask;
import cn.gong.http.callback.HttpCallBack;
import cn.gong.store.db.callback.DBCallBack;
import cn.gong.ui.R;
import cn.gong.utils.LogUtils;

public class BaseAct extends Activity implements OnClickListener, OnClick, HttpCallBack, DBCallBack, Base, ActID {
	// act的id，不会重复
	private int actID;
	private ActManager actManager;
	private SparseArray<Method> methods;

	@Override
	public int getActID() {
		return actID;
	}

	@Override
	public void setActID(int actID) {
		this.actID = actID;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			// 强制竖屏
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			// 在ActivityManager中注册
			actManager = ActManager.getInstance();
			actManager.addAct(this);
			// 异步网络请求
			methods = new SparseArray<Method>();
			onCreateAct(savedInstanceState);
		} catch (Exception e) {
			exception(e);
		}
	}

	// 替代onCreate方法
	protected void onCreateAct(Bundle savedInstanceState) {

	}

	// 设置布局 及各种view注入、点击监听。
	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		inject();
	}

	@Override
	public void setContentView(View view) {
		super.setContentView(view);
		inject();
	}

	@Override
	public void setContentView(View view, LayoutParams params) {
		super.setContentView(view, params);
		inject();
	}

	private void inject() {
		injectView();
		clickMethod();
	}

	// 查找布局
	private void injectView() {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			InjectView annotation = field.getAnnotation(InjectView.class);
			if (annotation != null) {
				int value = annotation.value();
				View view = findViewById(value);
				try {
					field.setAccessible(true);
					field.set(this, view);
				} catch (Exception e) {
					log("异常:fieldName:" + field.getName());
					exception(e);
				}
			}
		}
	}

	private void clickMethod() {
		Method[] methods = this.getClass().getDeclaredMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			Annotation[] annotations = method.getAnnotations();
			for (Annotation annotation : annotations) {
				Class type = annotation.annotationType();
				if (type == ClickMethod.class) {
					ClickMethod methodAnno = (ClickMethod) annotation;
					int[] values = methodAnno.value();
					for (int viewID : values) {
						this.methods.put(viewID, method);
						View view = findViewById(viewID);
						if (view != null) {
							view.setOnClickListener(this);
						}
					}
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		Method method = methods.get(v.getId());
		try {
			if (method != null) {
				method.setAccessible(true);
				method.invoke(this, v);
			}
		} catch (Exception e) {
			log("异常：methodName:" + method.getName());
			exception(e);
		}
	}

	// onStart
	@Override
	protected void onStart() {
		super.onStart();
		try {
			// 保存当前act
			ActManager.CURRENT_ACTID = actID;
			onStartAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	// 替代onStart方法
	protected void onStartAct() {
	}

	@Override
	public void onResume() {
		super.onResume();
		try {
			// 恢复暂时储存的数据
			onDateRecovery();
			onResumeAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	protected void onResumeAct() {
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		try {
			onRestartAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	protected void onRestartAct() {
	}

	@Override
	public void onPause() {
		super.onPause();
		try {
			// 清理并暂时缓存数据
			onDateClear();
			onPauseAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	protected void onPauseAct() {
	}

	// 清理并暂时缓存数据
	protected void onDateClear() {
	}

	// 恢复暂时储存的数据
	protected void onDateRecovery() {
	}

	@Override
	protected void onStop() {
		super.onStop();
		try {
			onStopAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	protected void onStopAct() {
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			// 移除act
			actManager.deleteAct(this);
			onDestroyAct();
		} catch (Exception e) {
			exception(e);
		}

	}

	protected void onDestroyAct() {
	}

	//
	protected int adjustSize(int ori) {
		return ori * PhoneParameters.screenWidth / PhoneParameters.designWidth;
	}

	protected float adjustTextSize(int ori) {
		return (ori * PhoneParameters.screenWidth) / (PhoneParameters.designWidth * PhoneParameters.density);
	}

	protected AlertDialog getAlertDialog() {
		AlertDialog myDialog = new AlertDialog.Builder(this).create();
		myDialog.show();
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		myDialog.getWindow().setContentView(inflate(R.layout.progress), lp);
		myDialog.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					return true;
				}
				return false;
			}
		});
		return myDialog;
	}

	protected void dialogCancel(AlertDialog dialog) {
		if (dialog != null) {
			dialog.cancel();
			dialog = null;
		}
	}

	// httpCallBack
	@Override
	public void callBack(final HttpTask task) {
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				onCallBack(task);
			}
		});
	}

	@Override
	public void dbTaskFinish(final String methodName, final Object data) {
		this.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				onDbCallBack(methodName, data);
			}
		});
	}

	protected void onCallBack(HttpTask task) {
		String methodName = task.getBackMethod();
		try {
			Method method = getClass().getDeclaredMethod(methodName, HttpTask.class);
			if (method != null) {
				method.setAccessible(true);
				method.invoke(this, task);
			}
		} catch (Exception e) {
			log("异常:methodName:" + methodName);
			exception(e);
		}
	}

	protected void onDbCallBack(String methodName, Object data) {
		try {
			Method method = getClass().getDeclaredMethod(methodName, Object.class);
			methodName = method.getName();
			if (method != null) {
				method.setAccessible(true);
				method.invoke(this, data);
			}
		} catch (Exception e) {
			log("异常:methodName:" + methodName);
			exception(e);
		}
	}

	// openAct
	protected void openAct(Intent intent) {
		startActivity(intent);
	}

	protected void openAct(Class newActClass) {
		openAct(new Intent(this, newActClass));
	}

	protected void openActForResult(Class newActClass, int requestCode) {
		openActForResult(new Intent(this, newActClass), requestCode);
	}

	protected void openActForResult(Intent intent, int requestCode) {
		startActivityForResult(intent, requestCode);
	}

	// openAnim
	protected void animAlpha() {
		overridePendingTransition(R.anim.alpha0to100, R.anim.alpha100to0);
	}

	protected void animScaleOpen() {
		overridePendingTransition(R.anim.scale0to100, R.anim.scale100to100);
	}

	protected void animScaleClose() {
		overridePendingTransition(R.anim.scale100to100, R.anim.scale100to0);
	}

	protected void animTranslateTopIn() {
		overridePendingTransition(R.anim.translateyf100to0, R.anim.translatey0to100);
	}

	protected void animTranslateBottomIn() {
		overridePendingTransition(R.anim.translatey100to0, R.anim.translatey0tof100);
	}

	protected void animTranslateRightIn() {
		overridePendingTransition(R.anim.translatex100to0, R.anim.translatex0tof100);
	}

	protected void animTranslateLeftIn() {
		overridePendingTransition(R.anim.translatexf100to0, R.anim.translatex0to100);
	}

	// closeAct

	protected void closeAct() {
		finish();
	}

	protected void closeActForResultOk() {
		setResult(RESULT_OK);
		closeAct();
	}

	protected void closeActForResultOk(Intent data) {
		setResult(RESULT_OK, data);
		closeAct();
	}

	protected void closeAct(int resultCode) {
		setResult(resultCode);
		closeAct();
	}

	protected void closeAct(int resultCode, Intent data) {
		setResult(resultCode, data);
		closeAct();
	}

	// 获得this
	protected BaseAct getAct() {
		return this;
	}

	// 输入法隐藏或出现
	protected void inputHidden(EditText et) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
	}

	protected void inputShow(EditText et) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
		imm.showSoftInput(et, 0);
	}

	// toast方法
	protected void toast(final String msg) {
		// 主线程执行toast
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(BaseAct.this, msg, 1000).show();
			}
		});
	}

	// 退出程序
	public void alertExit() {
		AlertDialog.Builder ab = new AlertDialog.Builder(this);
		ab.setTitle("提示");
		ab.setMessage("确定退出吗?");
		ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// Intent it = new Intent(BaseAct.this, MainService.class);
				// getApplicationContext().stopService(it);

				ActManager manager = ActManager.getInstance();

				SparseArray<ActID> allAct = manager.getAllAct();
				for (int i = 0; i < allAct.size(); i++) {
					((Activity) allAct.valueAt(i)).finish();
				}

				manager.clearSize();
				// android.os.Process.killProcess(android.os.Process.myPid());
			}
		});
		ab.setNegativeButton("取消", null);
		ab.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					return true;
				}
				return false;
			}
		});
		ab.create().show();
	}

	// 设置点击
	@Override
	public void setClick(int viewID) {
		findViewById(viewID).setOnClickListener(this);
	}

	@Override
	public void setClick(int viewID, View view) {
		view.findViewById(viewID).setOnClickListener(this);
	}

	@Override
	public void setClick(View view) {
		view.setOnClickListener(this);
	}

	// 获得布局
	protected View inflate(int resourceId) {
		return LayoutInflater.from(getApplicationContext()).inflate(resourceId, null);
	}

	// 为控件设置文字
	protected void setText(TextView tv, String str) {
		tv.setText(str);
	}

	protected void setText(TextView tv, Object obj) {
		tv.setText(String.valueOf(obj));
	}

	// 打印信息
	@Override
	public void log(String msg) {
		LogUtils.log(msg, getClass());
	}

	@Override
	public void log(Object msg) {
		log(String.valueOf(msg));
	}

	@Override
	public void isNull(String name, Object obj) {
		log(name + "==null:" + (obj == null));
	}

	@Override
	public void exception(Exception e) {
		LogUtils.exception(e);
	}

	// 一些获取View的方法
	protected LinearLayout findLinearLayoutById(int id) {
		return (LinearLayout) findViewById(id);
	}

	protected LinearLayout findLinearLayoutById(int id, View view) {
		return (LinearLayout) view.findViewById(id);
	}

	protected ListView findListViewById(int id) {
		return (ListView) findViewById(id);
	}

	protected ListView findListViewById(int id, View view) {
		return (ListView) view.findViewById(id);
	}

	protected Button findButtonById(int id) {
		return (Button) findViewById(id);
	}

	protected Button findButtonById(int id, View view) {
		return (Button) view.findViewById(id);
	}

	protected ProgressBar findProgressBarById(int id) {
		return (ProgressBar) findViewById(id);
	}

	protected ProgressBar findProgressBarById(int id, View view) {
		return (ProgressBar) view.findViewById(id);
	}

	protected ImageView findImageViewById(int id) {
		return (ImageView) findViewById(id);
	}

	protected ImageView findImageViewById(int id, View view) {
		return (ImageView) view.findViewById(id);
	}

	protected RelativeLayout findRelativeLayoutById(int id) {
		return (RelativeLayout) findViewById(id);
	}

	protected RelativeLayout findRelativeLayoutById(int id, View view) {
		return (RelativeLayout) view.findViewById(id);
	}

	protected TextView findTextViewById(int id) {
		return (TextView) findViewById(id);
	}

	protected TextView findTextViewById(int id, View view) {
		return (TextView) view.findViewById(id);
	}

	protected CheckBox findCheckBoxById(int id) {
		return (CheckBox) findViewById(id);
	}

	protected CheckBox findCheckBoxById(int id, View view) {
		return (CheckBox) view.findViewById(id);
	}

	protected FrameLayout findFrameLayoutById(int id) {
		return (FrameLayout) findViewById(id);
	}

	protected FrameLayout findFrameLayoutById(int id, View view) {
		return (FrameLayout) view.findViewById(id);
	}

	protected ImageButton findImageButtonById(int id) {
		return (ImageButton) findViewById(id);
	}

	protected ImageButton findImageButtonById(int id, View view) {
		return (ImageButton) view.findViewById(id);
	}

	protected EditText findEditTextById(int id) {
		return (EditText) findViewById(id);
	}

	protected EditText findEditTextById(int id, View view) {
		return (EditText) view.findViewById(id);
	}

	//
	protected void viewVisible(int id, View itemView) {
		itemView.findViewById(id).setVisibility(View.VISIBLE);
	}

	protected void viewVisible(View view) {
		view.setVisibility(View.VISIBLE);
	}

	protected void viewVisible(int id) {
		findViewById(id).setVisibility(View.GONE);
	}

	protected void viewGone(int id, View itemView) {
		itemView.findViewById(id).setVisibility(View.GONE);
	}

	protected void viewGone(View view) {
		view.setVisibility(View.GONE);
	}

	protected void viewGone(int id) {
		findViewById(id).setVisibility(View.GONE);
	}

	// 返回按钮默认事件
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return onKeyDownBackNormal(keyCode, event);
	}

	private boolean onKeyDownBackNormal(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			closeAct();
			animTranslateLeftIn();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected boolean onKeyDownBackExit(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			alertExit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
